package net.zoneland.zrdp.web.controller.system;

import static net.zoneland.zrdp.common.core.domain.AjaxResult.error;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;
import java.util.Set;

import net.zoneland.zrdp.common.utils.httpClient.HttpClientUtils;
import net.zoneland.zrdp.framework.web.service.HttpClientService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import net.zoneland.zrdp.common.config.ZonevueConfig;
import net.zoneland.zrdp.common.constant.Constants;
import net.zoneland.zrdp.common.core.domain.AjaxResult;
import net.zoneland.zrdp.common.core.domain.entity.SysMenu;
import net.zoneland.zrdp.common.core.domain.entity.SysUser;
import net.zoneland.zrdp.common.core.domain.model.LoginBody;
import net.zoneland.zrdp.common.utils.SecurityUtils;
import net.zoneland.zrdp.framework.web.service.SysLoginService;
import net.zoneland.zrdp.framework.web.service.SysPermissionService;
import net.zoneland.zrdp.system.service.ISysMenuService;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;

/**
 * 登录验证
 *
 * @author zonevue
 */
@RestController
public class SysLoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SysLoginController.class);
    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private ZonevueConfig zonevueConfig;

    /**
     * httpClient服务
     */
    @Resource
    private HttpClientService httpClientService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody final LoginBody loginBody) {
        try {
            final AjaxResult ajax = AjaxResult.success();
            final String decUserName =
                SecurityUtils.decryptAES(loginBody.getUsername(), zonevueConfig.getSecretKey(), zonevueConfig.getIv());
            final String decPassword =
                SecurityUtils.decryptAES(loginBody.getPassword(), zonevueConfig.getSecretKey(), zonevueConfig.getIv());
            // 生成令牌
            final String token = loginService.login(decUserName, decPassword, loginBody.getCode(),
                loginBody.getUuid());
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } catch (final NoSuchPaddingException |
                       NoSuchAlgorithmException | InvalidKeyException | BadPaddingException |
                       IllegalBlockSizeException |
                       InvalidAlgorithmParameterException e) {
            LOGGER.error("登录失败：{}", loginBody, e);
            return error(StringUtils.defaultIfBlank(e.getMessage(), "用户或密码错误！"));
        }
    }
    @GetMapping("/ssoLogin")
    public AjaxResult ssoLogin(final HttpServletRequest request) {
        final AjaxResult ajax = AjaxResult.success();
        if (zonevueConfig.isSsoEnabled()) {
            //尝试通过 cookie 获取 用户信息。 如果能获取到用户信息那么就创建一个token
            final String userId = httpClientService.getLoginedUserId(request.getHeader(HttpClientUtils.HEADER_KEY_COOKIE));
            final String token = Optional.ofNullable(userId).filter(StringUtils::isNotBlank).map(loginService::ssoLogin).orElse(null);
            ajax.put(Constants.TOKEN, token);
        } else {
            final String msg = "sso 未启用！";
            ajax.put("msg", msg);
        }
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        final SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        final Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        final Set<String> permissions = permissionService.getMenuPermission(user);
        final AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        final Long userId = SecurityUtils.getUserId();
        final List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
